const BaseIpcHandler = require('../BaseIpcHandler');
const ELECTRON_ENV = process.env.ELECTRON_ENV;

let dialog = null;
if (ELECTRON_ENV) {
    dialog = require('electron').dialog;
}

class OpenDirectoryHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> OpenDirectoryHandler params = ', params);

        // 业务逻辑
        let result = { code: -2, msg: 'Not in Electron Environment!' };
        if (ELECTRON_ENV && dialog) {
            try {
                const { canceled, filePaths } = await dialog.showOpenDialog({
                    properties: ['openDirectory']
                });
                if (!canceled && filePaths.length > 0) {
                    result = { code: 0, msg: filePaths[0] };
                } else {
                    result = { code: -1, msg: 'No directory selected.' };
                }
            } catch (error) {
                result = { code: -3, msg: `Dialog error: ${error.message}` };
            }
        }

        // 返回结果
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = OpenDirectoryHandler;
